const { merge } = require('webpack-merge');

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

const baseWebpackConfig = require('./webpack.base.conf.js');
const common = require('./common.js');

const prodWebpackConfig = merge(baseWebpackConfig, {
  mode: 'production',
  devtool: 'cheap-module-source-map',
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
      },
      {
        test: /\.scss$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
      },
      {
        test: /\.less$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'less-loader']
      },
    ]
  },

  plugins: [
    new CleanWebpackPlugin(),
    
    new MiniCssExtractPlugin({ // 使用，配合 loader 中配置提取 css 到单独文件，通过 link 引入
      filename: '[name].[contenthash:8].css', // 重命名提取的 css 名称
      chunkFilename: '[id].[contenthash:8].css',
    })
  ],

  optimization: {
    splitChunks: {
      chunks: 'all', // 所有文件中公共模块分离出来
      cacheGroups: {
        commoncss: { // 对公共的 css 分离提取
          name: 'vender-common-css',
          test: /\.css$/,
          chunks: 'all',
          enforce: true
        },
        asyncjs: { // 对异步懒加载的资源的 js 分离提取
          name: 'vender-async-js',
          test: /\.js$/,
          chunks: 'async',
          priority: -10,
        },
        commonjs: { // 对公共的 js 分离提取
          name: 'vender-common-js',
          test: /\.js$/,
          chunks: 'all',
          enforce: true
        },
      }
    },
    minimizer: [
      new CssMinimizerPlugin(),
    ],
  },
})


if (common.analyzer) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  prodWebpackConfig.plugins.push(new BundleAnalyzerPlugin());
}

if (common.compress) {
  const CompressioWebpacknPlugin = require("compression-webpack-plugin");
  prodWebpackConfig.plugins.push(new CompressioWebpacknPlugin());
}
module.exports = prodWebpackConfig;